#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2011/06/06

'''
from UserCommentDetail import UserCommentDetail
from UserCommentKeyword import UserCommentKeyword
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
import dateutil.parser
import gdata.spreadsheet.service
import os
import string
import sys
import traceback
import datetime

class MainPage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            if self.gd_client is None:
                self.login(user)
            self.response.headers['Content-Type'] = 'text/html;UTF-8'
            
            date = self.request.get('date')
            word = self.request.get('word', None)
            navbar = u''
            if word is None:
                feed = self.gd_client.GetWorksheetsFeed(UserCommentKeyword.key)
                id =  feed.entry[0].id.text.rsplit('/', 1)[1]
                userCommentkeyword = UserCommentKeyword(id)
                navbar = userCommentkeyword.outCommentKeyword(self.gd_client)
            else:
                feed = self.gd_client.GetWorksheetsFeed(UserCommentDetail.key)
                entry = feed.entry[0];
                id =  entry.id.text.rsplit('/', 1)[1]
            #    rowCount = entry.row_count.text
                userCommentDetail = UserCommentDetail(id)
                navbar = userCommentDetail.outComment(date, word, self.gd_client)
            
            data = { "comment_table":navbar, "sign_out_url": users.create_logout_url(self.request.path)}
            path = os.path.join( os.path.dirname( __file__ ), "user_comment_detail.html" )
            html = template.render(path, data)
            self.response.headers['Content-Type'] = 'text/html'
            self.response.out.write(html)
        else:
            self.redirect(users.create_login_url(self.request.uri))
        
    def post(self):
        user = users.get_current_user()
        if user:
            try:
                if self.gd_client is None:
                    self.login(user)
                self.response.headers['Content-Type'] = 'text/html;UTF-8'
                
                type = self.request.get('type', None)
                minDate = self.request.get('min_date', "2011/04/30")
                indexDate = self.request.get('index_date', minDate)
                maxDate = self.request.get('max_date', "2011/08/31")
                if type == 'keyword':
                    feed = self.gd_client.GetWorksheetsFeed(UserCommentKeyword.key)
                    id =  feed.entry[0].id.text.rsplit('/', 1)[1]
                    userCommentkeyword = UserCommentKeyword(id)
                    maxDate, minDate = userCommentkeyword.updateCommentKeyword(self.gd_client)
                    path = os.path.join( os.path.dirname( __file__ ), "update_keyword.html" )
                    data = { "max_date":maxDate, "min_date":minDate }
                    html = template.render(path, data)
                    self.response.headers['Content-Type'] = 'text/html'
                    self.response.out.write(html)
                elif type == 'comment':
                    feed = self.gd_client.GetWorksheetsFeed(UserCommentDetail.key)
                    entry = feed.entry[0];
                    id =  entry.id.text.rsplit('/', 1)[1]
                    userCommentDetail = UserCommentDetail(id)
                    isClear = True
                    if minDate != indexDate:
                        isClear = False
                    userCommentDetail.updateComment(self.gd_client, isClear, indexDate)
                    tempDate = dateutil.parser.parse(indexDate)
                    nextDate = tempDate + datetime.timedelta(1)
                    laod_continue = 'document.MyForm.submit()'
                    tempMaxDate = dateutil.parser.parse(maxDate)
                    if tempMaxDate < nextDate:
                        self.redirect('/')
                    else:
                        strDate = nextDate.strftime('%Y/%m/%d')
                        data = { "load_continue":laod_continue, "max_date":maxDate, "index_date":strDate, "min_date":minDate }
                        path = os.path.join( os.path.dirname( __file__ ), "update_comment.html" )
                        html = template.render(path, data)
                        self.response.headers['Content-Type'] = 'text/html'
                        self.response.out.write(html)
            except Exception:
                message = []
                message.append('<pre>')
                value = " Error \n %s:%s" % (sys.exc_info()[0], sys.exc_info()[1])
                message.append(value)
                message.append('</pre>')
                navbar = "".join(message)
                data = { "comment_table":navbar, "sign_out_url": users.create_logout_url(self.request.path)}
                path = os.path.join( os.path.dirname( __file__ ), "user_comment_detail.html" )
                html = template.render(path, data)
                self.response.headers['Content-Type'] = 'text/html'
                self.response.out.write(html)
        else:
            self.redirect(users.create_login_url(self.request.uri))

    gd_client = None
    def login(self, user):
        if self.gd_client is None:
            gd_client = gdata.spreadsheet.service.SpreadsheetsService()
            gd_client.email = user.email()
            gd_client.password = 'testuser58841234'
            gd_client.debug = True
            gd_client.ProgrammaticLogin()
        
            self.gd_client = gd_client

def getWorksSheetId(key, gd_client):
    feed = gd_client.GetWorksheetsFeed(key)
    #input = raw_input('\nSelection: ')
    input = '0'
    wksht_id = feed.entry[string.atoi(input)].id.text.rsplit('/', 1)[1]
    
    return wksht_id

application = webapp.WSGIApplication([('/', MainPage),('/detail', MainPage), ('/update', MainPage)], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
